package function

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/x509"
	"encoding/pem"
	"flag"
	"fmt"
	"log"
	"os"
)

func GenEcckey(){
	var bits int
	flag.IntVar(&bits,"b",2048,"密钥长度默认1024")
	for i:=6;i<23;i++{
		if err:=GenKey(bits,i);err!=nil{
			log.Fatal("fail")
		}
	}
	log.Fatal("success")
}

func GenKey(bits int,seq int) interface{} {
	prikeyName:="C:/Users/00/go/src/blockchain/public/key/private"+fmt.Sprint(seq)+".pem"
	pubkeyName:="C:/Users/00/go/src/blockchain/public/key/public"+fmt.Sprint(seq)+".pem"
	curve:=elliptic.P256()
	private,err:=ecdsa.GenerateKey(curve,rand.Reader)
	if err !=nil{
		log.Panic(err)
	}
	derStream,err:=x509.MarshalECPrivateKey(private)
	if err !=nil{
		log.Panic(err)
	}
	block:=&pem.Block{
		Type:"私钥",
		Bytes:derStream,
	}
	file,err:=os.Create(prikeyName)
	if err!=nil{
		println("wenjian：私钥")
		return err
	}
	err=pem.Encode(file,block)
	if err!=nil{
		return err
	}
	pubkey:=append(private.X.Bytes(),private.Y.Bytes()...)
	derPkix:=pubkey
	block=&pem.Block{
		Type:"公钥",
		Bytes:derPkix,
	}
	file,err=os.Create(pubkeyName)
	if err!=nil{
		return err
	}
	err=pem.Encode(file,block)
	if err!=nil{
		return err
	}
	return nil
}

